package com.ogawa.projectcommon.dialog;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentManager;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadLargeFileListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.ogawa.base.utils.FileUtils;
import com.ogawa.base.widget.ProgressButton;
import com.ogawa.projectcommon.R;
import com.ogawa.projectcommon.bean.UpdateResponseBean;
import com.ogawa.projectcommon.utils.VersionUtils;


import java.io.File;

import static android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
import static com.ogawa.base.constants.Constants.MainFileProvider_Authorities;
import static com.ogawa.base.utils.StringPrintUtilsKt.printNoNull;


public class ShowUpdateDialog {
    private Context context;
    View view;
    AlertDialog mViewDialog;

    public ShowUpdateDialog(Activity context, UpdateResponseBean response, ShowUpdateDialogCallBack callBack){
        this.context = context;
        String LocalPath = FileUtils.getRootPath()  + "/joypal.apk";

        view = LayoutInflater.from(context).inflate(R.layout.dialog_update, null);
        ProgressButton buttonShengJi = view.findViewById(R.id.buttonShengJi);
        view.findViewById(R.id.CancleTv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(response.getIsforce())){
                    ToastUtils.showShort(R.string.is_force_update);
                }else {
                    callBack.noUpdate(ShowUpdateDialog.this);
                }

            }
        });
        TextView titleTv = view.findViewById(R.id.dialog_shengji_version_title_tv);
        TextView versionTv = view.findViewById(R.id.dialog_shengji_version_tv);
        TextView contentMessageTv = view.findViewById(R.id.contentMessageTv);


        String versionStr = VersionUtils.versionToVersionName(response.getAppversion());
        versionTv.setText(printNoNull(context.getString(R.string.new_version) + versionStr));
        contentMessageTv.setText(printNoNull(response.getNotice()));
        contentMessageTv.setMovementMethod(ScrollingMovementMethod.getInstance());
        buttonShengJi.setMaxProgress(100);
        buttonShengJi.setMinProgress(0);

        String finalLocalPath = LocalPath;
        String finalLocalPath1 = LocalPath;
        buttonShengJi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buttonShengJi.setProgress(0);
                File file = new File(finalLocalPath);
                try {
                    if (file.exists()){
                        file.delete();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                buttonShengJi.setEnabled(false);
                view.findViewById(R.id.CancleTv).setEnabled(false);
                buttonShengJi.setText(R.string.update_start_up);
                FileDownloader.setup(context);
                FileDownloader.getImpl().create(response.getUrl())
                        .setPath(finalLocalPath)
                        .setListener(new FileDownloadLargeFileListener() {
                            @Override
                            protected void pending(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                            }

                            @Override
                            protected void progress(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                                int progress = (int) (soFarBytes * 100 / totalBytes);
                                if (progress < 100){
                                    buttonShengJi.setProgress(progress);
                                    buttonShengJi.setText("" + progress + "%");
                                }
                            }

                            @Override
                            protected void paused(BaseDownloadTask task, long soFarBytes, long totalBytes) {

                            }

                            @Override
                            protected void completed(BaseDownloadTask task) {
                                buttonShengJi.setProgress(100);
                                buttonShengJi.setText(context.getString(R.string.complete));
                                try{
                                    installApk(context, finalLocalPath);
                                }catch (Exception e){
                                    e.printStackTrace();
                                    ToastUtils.showShort(context.getString(R.string.auto_install_err) + finalLocalPath1);
                                }
                                dismiss();
                                context.finish();
                            }

                            @Override
                            protected void error(BaseDownloadTask task, Throwable e) {
                                ToastUtils.showShort(context.getString(R.string.check_update_file_down_err));
                                dismiss();
                                context.finish();
                            }

                            @Override
                            protected void warn(BaseDownloadTask task) {
                            }
                        }).start();



            }
        });
        mViewDialog =new AlertDialog.Builder(context).setCancelable(false).create();

        mViewDialog.setView(view);
    }
    public void show() {
        mViewDialog.show();
    }


    public void dismiss(){
        if (mViewDialog != null){
            mViewDialog.dismiss();
        }
    }

    public static  void installApk(Context context,String downloadApk) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(downloadApk);
        LogUtils.e("安装路径=="+downloadApk);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION| FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri apkUri = FileProvider.getUriForFile(context, MainFileProvider_Authorities, file);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        }
        context.startActivity(intent);

    }



    public interface ShowUpdateDialogCallBack{
        void noUpdate(ShowUpdateDialog showUpdateDialog);
    }


}
